<template>
  <div class="cs-assignment">
    <div class="cs-header">
      <h3>客服分配</h3>
    </div>
    
    <div class="cs-list">
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="customerServices.length === 0" class="no-cs">
        暂无可用客服
      </div>
      <div v-else class="cs-items">
        <div 
          v-for="cs in customerServices" 
          :key="cs.id"
          class="cs-item"
        >
          <div class="cs-info">
            <div class="cs-avatar">
              <img :src="cs.avatar || '/default-avatar.png'" alt="客服头像">
            </div>
            <div class="cs-details">
              <div class="cs-name">{{ cs.nickname || cs.username }}</div>
              <div class="cs-status">
                <span class="status-dot" :class="{ 'active': cs.status === 1 }"></span>
                {{ cs.status === 1 ? '在线' : '离线' }}
              </div>
            </div>
          </div>
          <div class="cs-stats">
            <div class="cs-conversation-count">
              当前会话数: {{ csConversationCounts[cs.id] || 0 }}
            </div>
          </div>
          <div class="cs-actions">
            <button 
              class="assign-btn" 
              @click="assignCustomerService(cs.id)"
              :disabled="cs.status !== 1"
            >
              分配
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';

export default {
  name: 'CustomerServiceAssignment',
  props: {
    userId: {
      type: Number,
      required: true
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const customerServices = ref([]);
    const loading = ref(true);
    const csConversationCounts = reactive({});
    const userRoles = ref([]);
    
    // 获取用户角色
    const fetchUserRoles = async () => {
      if (!props.userId) return;
      
      try {
        const response = await axios.get(`/api/chat/cs/roles/${props.userId}`);
        if (response.data.code === 200) {
          userRoles.value = response.data.data || [];
          console.log('用户角色:', userRoles.value);
        }
      } catch (error) {
        console.error('获取用户角色失败:', error);
      }
    };
    
    // 获取所有客服列表
    const fetchCustomerServices = async () => {
      try {
        loading.value = true;
        console.log('正在获取客服列表...');
        const response = await axios.get('/api/chat/cs/list');
        console.log('客服列表响应:', response);
        if (response.data.code === 200) {
          customerServices.value = response.data.data || [];
          console.log('获取到的客服列表:', customerServices.value);
          // 获取每个客服的会话数
          for (const cs of customerServices.value) {
            fetchCsConversationCount(cs.id);
          }
        }
      } catch (error) {
        console.error('获取客服列表失败:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 获取客服的当前会话数
    const fetchCsConversationCount = async (csUserId) => {
      try {
        const response = await axios.get(`/api/chat/cs/conversation-count/${csUserId}`);
        if (response.data.code === 200) {
          csConversationCounts[csUserId] = response.data.data;
        }
      } catch (error) {
        console.error('获取客服会话数失败:', error);
      }
    };
    
    // 分配客服
    const assignCustomerService = async (csUserId) => {
      try {
        const response = await axios.post(`/api/chat/cs/assign/${props.userId}`);
        if (response.data.code === 200) {
          emit('assigned', response.data.data);
        }
      } catch (error) {
        console.error('分配客服失败:', error);
      }
    };
    
    // 自动分配客服
    const autoAssignCustomerService = async () => {
      try {
        const response = await axios.post(`/api/chat/cs/assign/${props.userId}`);
        if (response.data.code === 200) {
          emit('assigned', response.data.data);
        }
      } catch (error) {
        console.error('自动分配客服失败:', error);
      }
    };
    
    onMounted(() => {
      console.log('CustomerServiceAssignment组件已挂载，用户ID:', props.userId, '是否管理员:', props.isAdmin);
      fetchCustomerServices();
      fetchUserRoles();
      
      // 自动分配客服，只有非管理员用户才自动分配
      if (props.userId && !props.isAdmin) {
        autoAssignCustomerService();
      } else if (!props.userId) {
        console.warn('未提供用户ID，无法自动分配客服');
      }
    });
    
    return {
      customerServices,
      loading,
      csConversationCounts,
      assignCustomerService,
      userRoles
    };
  }
}
</script>

<style scoped>
.cs-assignment {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.cs-header {
  padding: 12px 16px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.cs-header h3 {
  margin: 0;
  font-size: 16px;
}

.cs-list {
  padding: 16px;
}

.loading, .no-cs {
  text-align: center;
  padding: 20px 0;
  color: #666;
}

.cs-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.cs-item:last-child {
  border-bottom: none;
}

.cs-info {
  display: flex;
  align-items: center;
}

.cs-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

.cs-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cs-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.cs-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ccc;
  margin-right: 6px;
}

.status-dot.active {
  background-color: #4caf50;
}

.cs-stats {
  font-size: 12px;
  color: #666;
}

.assign-btn {
  padding: 6px 12px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.assign-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>